<template>
  <div class="knowledge-container">
    <!-- 左侧知识库列表 -->
    <div class="knowledge-base-list">
      <DynamicTable
        row-key="id"
        header-title="知识库管理"
        :data-request="Api.knowledgeBase.knowledgeBaseList"
        :columns="columns"
        bordered
        size="small"
        :row-class-name="getRowClassName"
        :custom-row="customRow"
      >
        <template #toolbar>
          <a-button
            type="primary"
            @click="openMenuModal({})"
          >
            新增知识库
          </a-button>
        </template>
      </DynamicTable>
    </div>
    
    <!-- 右侧知识库文件列表 -->
    <div class="knowledge-file-list">
      <div class="knowledge-file-header">
        <h4>{{ selectedKnowledgeBase ? `文件列表: ${selectedKnowledgeBase.name}` : '请选择知识库' }}</h4>
        <div class="knowledge-file-header-actions">
          <a-input-search
            v-if="selectedKnowledgeBase"
            placeholder="搜索文件"
            style="width: 200px; margin-right: 8px;"
            @search="handleSearchFile"
          />
          <a-button 
            type="primary" 
            size="small"
            :disabled="!selectedKnowledgeBase"
            @click="openFileModal({knowledgeBaseId: selectedKnowledgeBaseId})"
          >
            上传文件
          </a-button>
        </div>
      </div>
      
      <KnowledgeFileTable
        v-if="selectedKnowledgeBase"
        row-key="id"
        :data-source="knowledgeFileList"
        :columns="knowledgeFileColumnsWithAction"
        bordered
        size="small"
        :immediate="false"
        :search="false"
        :show-tool-bar="false"
        :pagination="knowledgeFilePagination"
        ref="knowledgeFileTableRef"
      >
       
      </KnowledgeFileTable>
      
      <div v-else class="empty-knowledge-files">
        <a-empty description="请先选择左侧知识库" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, h, getCurrentInstance, onMounted, nextTick, computed } from 'vue';
  import { baseColumns as knowledgeFileColumns } from '../knowledge-file/columns';
  import {
    baseColumns,
    searchFormSchema,
    type TableListItem,
    type TableColumnItem,
  } from './columns';
  import { baseSchemas } from './formSchemas';
  import { useTable } from '@/components/core/dynamic-table';
  import { useFormModal } from '@/hooks/useModal/';
  import Api from '@/api/';
  import { baseSchemas as knowledgeFileSchemas } from '../knowledge-file/formSchemas';
  import helper from '@/utils/helper';

  // 声明ApiResponse接口，用于处理API返回的数据
  interface ApiResponse {
    items: any[];
    meta?: {
      totalItems: number;
    };
    [key: string]: any;
  }

  defineOptions({
    name: 'KnowledgeBase',
  });

  // 获取全局属性
  const app = getCurrentInstance();
  const $auth = app?.appContext.config.globalProperties.$auth;

  const knowledgeBaseList = ref<any[]>([]);
  const knowledgeFileList = ref<any[]>([]);
  const knowledgeFileLoading = ref<boolean>(false);
  const selectedKnowledgeBase = ref<TableListItem | null>(null);
  const selectedKnowledgeBaseId = ref<string | null>(null);
  const knowledgeFilePagination = ref({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `共 ${total} 条`,
    onChange: (page: number, pageSize: number) => {
      knowledgeFilePagination.value.current = page;
      knowledgeFilePagination.value.pageSize = pageSize;
      if (selectedKnowledgeBaseId.value) {
        loadKnowledgeFiles(selectedKnowledgeBaseId.value);
      }
    }
  });

  const [DynamicTable, dynamicTableInstance] = useTable({
    formProps: {
      schemas: searchFormSchema,
    },
  });

  // 创建右侧知识库文件表格实例
  const [KnowledgeFileTable, knowledgeFileTableInstance] = useTable({
    formProps: {
      schemas: [],
    },
  });

  const [showModal] = useFormModal();

  // 搜索关键词
  const searchKeyword = ref('');

  /**
   * @description 获取行样式
   */
  const getRowClassName = (record: TableListItem) => {
    return record.id === selectedKnowledgeBaseId.value ? 'selected-row' : '';
  };

  /**
   * @description 自定义行属性
   */
  const customRow = (record: TableListItem) => {
    return {
      onClick: () => handleRowClick(record),
    };
  };

  /**
   * @description 点击知识库行
   */
  const handleRowClick = (record: TableListItem) => {
    selectedKnowledgeBase.value = record;
    selectedKnowledgeBaseId.value = record.id;
    
    // 重置分页到第一页
    knowledgeFilePagination.value.current = 1;
    
    // 重置搜索关键词
    searchKeyword.value = '';
    
    loadKnowledgeFiles(record.id);
  };

  /**
   * @description 处理文件搜索
   */
  const handleSearchFile = (value: string) => {
    searchKeyword.value = value;
    knowledgeFilePagination.value.current = 1;
    if (selectedKnowledgeBaseId.value) {
      loadKnowledgeFiles(selectedKnowledgeBaseId.value);
    }
  };

  /**
   * @description 加载知识库文件
   */
  const loadKnowledgeFiles = async (knowledgeBaseId: string, extraParams: Record<string, any> = {}) => {
    knowledgeFileLoading.value = true;
    try {
      // 加载知识库列表（如果尚未加载）
      if (knowledgeBaseList.value.length === 0) {
        const data = await Api.knowledgeBase.knowledgeBaseGetAll();
        knowledgeBaseList.value = data.map((n) => ({ label: n.name, value: n.id }));
      }
      
      // 获取分页参数
      const { current, pageSize } = knowledgeFilePagination.value;
      
      // 请求后端分页数据
      const requestParams = {
        knowledgeBaseId,
        index: current,
        pageSize: pageSize,
        fileName: searchKeyword.value,
        ...extraParams
      };
      
      const response = await Api.knowledgeFile.knowledgeFileList(requestParams) as ApiResponse;
      
      // 更新列表数据
      knowledgeFileList.value = response.items || [];
      
      // 更新分页总数
      if (response.meta) {
        knowledgeFilePagination.value.total = response.meta.totalItems || 0;
      }
    } finally {
      knowledgeFileLoading.value = false;
    }
  };

  /**
   * @description 打开新增/编辑知识库弹窗
   */
  const openMenuModal = async (record: Partial<TableListItem>) => {
    const [formRef] = await showModal({
      modalProps: {
        title: `${record.id ? '编辑' : '新增'}知识库`,
        width: '50%',
        onFinish: async (values) => {
          console.log('提交的表单数据:', values);
          if (record.id) {
            await Api.knowledgeBase.knowledgeBaseUpdate({ id: record.id }, values);
          } else {
            await Api.knowledgeBase.knowledgeBaseCreate(values);
          }

          dynamicTableInstance?.reload();
        },
      },
      formProps: {
        labelWidth: 120,
        schemas: baseSchemas,
      },
    });

    // 显示当前要编辑的值
    console.log('设置表单初始值:', record);
    formRef?.setFieldsValue({
      ...record,
    });
  };

  /**
   * @description 打开新增文件弹窗
   */
  const openFileModal = async (record: any) => {
    const [formRef] = await showModal({
      modalProps: {
        title: '上传文件',
        width: '50%',
        onFinish: async (values) => {
          if (record.id) {
            await Api.knowledgeFile.knowledgeFileUpdate({ id: record.id }, values);
          } else {
            await Api.knowledgeFile.knowledgeFileCreate(values);
          }
          if (selectedKnowledgeBaseId.value) {
            loadKnowledgeFiles(selectedKnowledgeBaseId.value);
          }
        },
      },
      formProps: {
        labelWidth: 120,
        schemas: knowledgeFileSchemas,
      },
    });

    formRef?.updateSchema({
      field: 'knowledgeBaseId',
      componentProps: {
        options: knowledgeBaseList.value,
        disabled: !!record.knowledgeBaseId,
      },
    });

    formRef?.setFieldsValue({
      ...record,
    });
  };

  /**
   * @description 删除知识库
   */
  const delKnowledgeBaseConfirm = async (record: TableListItem) => {
    await Api.knowledgeBase.knowledgeBaseDelete({ id: record.id });
    dynamicTableInstance?.reload();
    // 如果删除的是当前选中的知识库，清空右侧
    if (record.id === selectedKnowledgeBaseId.value) {
      selectedKnowledgeBase.value = null;
      selectedKnowledgeBaseId.value = null;
      knowledgeFileList.value = [];
    }
  };

  /**
   * @description 下载文件
   */
  const downloadFile = async (record: any) => {
    await Api.file.downloadex(record.fileMD5);
  };

  /**
   * @description 删除文件
   */
  const delFileConfirm = async (record: any) => {
    await Api.knowledgeFile.knowledgeFileDelete({ id: record.id });
    
    if (selectedKnowledgeBaseId.value) {
      loadKnowledgeFiles(selectedKnowledgeBaseId.value);
    }
  };
  /**
   * @description 向量化文件
   */
   const embedFile = async (record: TableListItem) => {
    try {
      await Api.knowledgeFile.knowledgeFileEmbedding(record.knowledgeBaseId, record.id);
      if (selectedKnowledgeBaseId.value) {
      loadKnowledgeFiles(selectedKnowledgeBaseId.value);
    }
    } catch (error) {
      console.error('向量化文件失败:', error);
    }
  };

  // 添加操作按钮到列
  const columns: TableColumnItem[] = [
    ...baseColumns,
    {
      title: '操作',
      width: 130,
      dataIndex: 'ACTION',
      hideInSearch: true,
      fixed: 'right',
      actions: ({ record }) => [
        {
          label: '编辑',
          onClick: () => openMenuModal(record),
        },
        {
          label: '删除',
          popConfirm: {
            title: '你确定要删除吗？',
            placement: 'left',
            onConfirm: () => delKnowledgeBaseConfirm(record),
          },
        },
      ],
    },
  ];

  // 添加文件操作按钮
  const knowledgeFileColumnsWithAction = computed(() => {
    return [
      ...knowledgeFileColumns,
      {
        title: '操作',
        width: 200,
        dataIndex: 'ACTION',
        hideInSearch: true,
        fixed: 'right',
        actions: ({ record }) => [
        {
          label: '编辑',
          onClick: () => openFileModal(record),
        },
        {
          label: '向量化',
          
          tooltip: record.isEmbedding ? '文件已向量化' : '',
          onClick: () => embedFile(record),
        },
          {
            label: '下载',
            onClick: () => downloadFile(record),
          },
          {
            label: '删除',
            popConfirm: {
              title: '你确定要删除吗？',
              placement: 'left',
              onConfirm: () => delFileConfirm(record),
            },
          },
        ],
      },
    ];
  });
</script>

<style lang="less" scoped>
.knowledge-container {
  display: flex;
  height: 100%;
  
  .knowledge-base-list {
    flex: 0 0 50%;
    width: 50%;
    padding-right: 8px;
    border-right: 1px solid #f0f0f0;
    overflow: auto;
    
    :deep(.selected-row) {
      background-color: #e6f7ff;
    }
  }
  
  .knowledge-file-list {
    flex: 0 0 50%;
    width: 50%;
    padding-left: 8px;
    overflow: auto;
    
    .knowledge-file-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8px;
      padding: 8px;
      background-color: #fafafa;
      border-radius: 4px;
      
      h4 {
        margin: 0;
      }
      
      .knowledge-file-header-actions {
        display: flex;
        align-items: center;
      }
    }
    
    .empty-knowledge-files {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 400px;
    }
  }
}
</style> 